package lab2rsagroup10;

import java.io.BufferedReader;
import java.io.FileReader;
import java.math.BigInteger;
import java.util.List;

public class Main {
	
        /**
	 *
         * Prints the usage of the program on the terminal.
	 *
	 */
	public static void usage() {
		System.err.println("Usage: [-e <message>] [-d <cipher> <modulo> <key>] [-b <path> <r-value>]");
		System.err.println("\t-e \t Encrypt.");
		System.err.println("\t-d \t Decrypt.");
		System.err.println("\t-b \t Break.");
	}

        /**
	 * The main function of the program.
	 * @param args - The arguments to the program
	 */
	public static void main(String[] args) {
		
		if (args.length < 1) {
			usage();
			return;
		}
		
		final String option = args[0];
		
		// The encryption of a message:
		if (option.equalsIgnoreCase("-e")) {
			if (args.length != 2) {
				usage();
				return;
			}
			
			final String message = args[1];
			RSA.Keys keys = RSA.generateKeys();
			
			List<BigInteger> ciphers = RSA.encrypt(message, keys.publicKey);
			
			System.out.println("Encrypted message (with public key):");
			for(BigInteger c : ciphers) {
				System.out.println(c.toString());
			}
			System.out.printf("\nModulos:\n%s" +
					"\n\nPrivate key:\n%s" +
					"\n\nPublic key:\n%s\n",
					keys.privateKey.modulos.toString(),
					keys.privateKey.key.toString(),
					keys.publicKey.key.toString());
		  
		} // The decryption of a message given the private key:
		else if (option.equalsIgnoreCase("-d")) {
			if (args.length != 4) {
				usage();
				return;
			}
			
			final String cipher = args[1];
			final String modulos = args[2];
			final String private_key_string = args[3];
			
			RSA.Key private_key = new RSA.Key(
					new BigInteger(private_key_string),
					new BigInteger(modulos));
			
			String decrypted = RSA.decrypt(
					new BigInteger(cipher), private_key);
			
			System.out.printf("Cipher:\n%s\nModulos:\n%s" +
					"\n\nPrivate key:\n%s\n\n", cipher, modulos, private_key_string);
			
			System.out.printf("Decrypted message: %s\n", decrypted);
		} // Breaking the ciphers given in the files:
		else if(option.equalsIgnoreCase("-b")) {
			if (args.length != 3) {
				usage();
				return;
			}
			final String file_path = args[1];
			int r_value = Integer.parseInt(args[2]);
			
			Lab2RSAParser parser;
			try {
				BufferedReader br = new BufferedReader(new FileReader(file_path));
				parser = new Lab2RSAParser(br);
			} catch(Exception e) {
				System.err.println(e.getMessage());
				return;
			}
			
			long timer_start = System.currentTimeMillis();
			String message = RSA.breakMessage(parser, r_value);
			long timer_end = System.currentTimeMillis();
			
			System.out.printf("MESSAGE FOUND:\n\t%s\n", message);
			System.out.printf("Elapsed time: %d", timer_end-timer_start);
		} else {
			usage();
		}
	}
}
